#define _CRT_SECURE_NO_WARNINGS 1
#include "DLList.h"
DLNode* DLBuyNode(DLDataType x)
{
	DLNode* new = malloc(sizeof(DLNode));
	if (new == NULL)
	{
		perror("申请空间失败");
	}
	else
	{
		new->data = x;
		new->next = new;
		new->prev = new;//此处实现的是双向循环有头链表,这样初始化(而非将已写过的其他Init()函数一样把这两个指针置空)是为了保证其循环性
	}
	return new;
}

DLNode* DLInit()
{
	DLNode* phead = DLBuyNode(0);
	return phead;
}

DLNode* DLDestroy(DLNode* phead)
{
	assert(phead);
	DLNode* pcur = phead->next;
	DLNode* pnext = pcur->next;
	while (pcur != phead)
	{
		free(pcur);
		pcur = pnext;
		pnext = pnext->next;
	}//此循环不会释放头节点
	free(phead);
	return NULL;
}

void DLPrint(DLNode* phead)
{
	assert(phead);
	DLNode* pcur = phead->next;
	while (pcur != phead)
	{
		printf("%d->", pcur->data);
		pcur = pcur->next;
	}
	printf("\n");
}

bool DLEmpty(DLNode* phead)
{
    assert(phead);
	if (phead->next == phead)
	{
		return true;
	}
	else
	{
		return false;
	}
}

void DLPushBack(DLNode* phead, DLDataType x)//prev new phead
{
    assert(phead);
	DLNode* new = DLBuyNode(x);
	DLNode* prev = phead->prev;
	new->next = phead;
	new->prev = prev;
	prev->next = new;
	phead->prev = new;
}

void DLPopBack(DLNode* phead)
{
    assert(phead);
	bool flag = DLEmpty(phead);
	if (flag)
	{
		exit(1);
	}
	else
	{
		DLNode* del = phead->prev;
		DLNode* prev = del->prev;
		free(del);
		prev->next = phead;
		phead->prev = prev;
	}
}

void DLPushFront(DLNode* phead, DLDataType x)
{
    assert(phead);
	DLNode* new = DLBuyNode(x);
	DLNode* next = phead->next;
	new->next = next;
	new->prev = phead;
	phead->next = new;
	next->prev = new;
}

void DLPopFront(DLNode* phead)//phead del next
{
    assert(phead);
	bool flag = DLEmpty(phead);
	if (flag)
	{
		exit(1);
	}
	else
	{
		DLNode* del = phead->next;
		DLNode* next = del->next;
		free(del);
		next->prev = phead;
		phead->next = next;
	}
}

DLNode* DLFind(DLNode* phead, DLDataType x)
{
    assert(phead);
	DLNode* pcur = phead->next;
	while (pcur != phead)
	{
		if (pcur->data == x)
		{
			return pcur;
		}
		pcur = pcur->next;
	}
	return NULL;
}

void DLInsert(DLNode* pos, DLDataType x)
{
	assert(pos);
	DLPushFront(pos, x);//由链表的循环性,在pos后插入数据等效为以pos为头节点进行头插
}

void DLErase(DLNode* pos)
{
	assert(pos);
	DLPopFront(pos);
}